//
//  CCSingleton.m
//  MXApp
//
//  Created by CC on 2017/9/7.
//  Copyright © 2017年 Shanghai YingXiang Network Technology Co., Ltd. All rights reserved.
//

#import "CCSingleton.h"

@interface CCSingleton () {
  BOOL _internalInited;
}

@end

@implementation CCSingleton

static NSMutableDictionary* instances;

+ (void)initialize {
  if (self == [CCSingleton self]) {
    instances = [NSMutableDictionary dictionary];
  }
}

+ (instancetype)allocWithZone:(struct _NSZone*)zone {
  NSString* clazzName = NSStringFromClass(self);
  @synchronized([CCSingleton self]) {
    id instance = instances[clazzName];
    if (instance == nil) {
      instance = [super allocWithZone:zone];
      instances[clazzName] = instance;
    }
    return instance;
  }
}

+ (instancetype)sharedInstance {
  NSString* clazzName = NSStringFromClass(self);
  @synchronized([CCSingleton self]) {
    CCSingleton* instance = instances[clazzName];
    if (instance == nil) {
      instance = [[self alloc] init];
      instances[clazzName] = instance;
    }
    if (!instance->_internalInited) {
      instance->_internalInited = YES;
      [instance internalInit];
    }
    return instance;
  }
}

- (void)internalInit {
}

@end
